package top.lvkun.pet.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lvkun.basic.domain.Point;
import top.lvkun.basic.service.impl.BaseServiceImpl;
import top.lvkun.basic.utils.AjaxResult;
import top.lvkun.basic.utils.DistanceUtil;
import top.lvkun.org.domain.Shop;
import top.lvkun.org.mapper.ShopMapper;
import top.lvkun.pet.domain.Adopt;
import top.lvkun.pet.domain.Pet;
import top.lvkun.pet.domain.PetDetail;
import top.lvkun.pet.mapper.AdoptMapper;
import top.lvkun.pet.mapper.PetMapper;
import top.lvkun.pet.service.IAdoptService;

import java.util.Date;
import java.util.List;

@Service
public class AdoptServiceImpl extends BaseServiceImpl<Adopt> implements IAdoptService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private AdoptMapper adoptMapper;
    @Autowired
    private PetMapper petMapper;
    /**
     * 前台用户 发布寻主信息
     * @param adopt
     */
    @Override
    public void publishAdopt(Adopt adopt) {
        //1.使用百度地图API 根据地址获取经纬度
        Point point = DistanceUtil.getPoint(adopt.getAddress());

        //2.查询附近所有商家店铺 得到List<Shop>集合
        List<Shop> shops = shopMapper.loadAll();

        //3.循环这个集合，查找一个距离发布人填写的地址最近的商家店铺
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        //4.adopt对象设置shop_id
        adopt.setShop_id(shop.getId());
        //5.保存adopt数据
        adoptMapper.save(adopt);
    }

    /**
     * 后台管理  商家处理寻主信息
     * @param id
     * @param handleResult
     * @return
     */
    @Override
    public AjaxResult handleAdopt(Long id, Integer handleResult) {
        if(handleResult==1){//1表示接受
            //通过id查询寻主信息
            Adopt adopt = adoptMapper.loadById(id);

            //设置该寻主消息已处理，且设置user_id为null表示该宠物不属于它主人了
            adopt.setState(0);
            adopt.setUser_id(null);
            adoptMapper.update(adopt);
            //创建pet对象，设置pet信息，保存到数据库中
            Pet pet = new Pet();
            pet.setName(adopt.getName());
            pet.setAdopt_id(id);
            pet.setShop_id(adopt.getShop_id());
            pet.setType_id(adopt.getPet_type());
            pet.setCostprice(adopt.getPrice());
            pet.setResources(adopt.getResources());
            pet.setCreatetime(new Date());
            pet.setState(1);//默认下架状态
            petMapper.save(pet);

            //保存宠物详情信息
            PetDetail petDetail = new PetDetail();
            petDetail.setPet_id(pet.getId());
            petDetail.setIntro(adopt.getTitle());
            petDetail.setAdoptNotice(adopt.getTitle() + "[毛色：" + adopt.getCoatColor().getName() + "，年龄：" + adopt.getAge() + "]");
            petMapper.savePetDetail(petDetail);
        }else {//拒绝

        }
        return AjaxResult.me();
    }
}
